const workModel = require('../models/workModel')
const userModel = require('../models/userModel')
const fs = require('fs')
const path = require('path')
const { Readable } = require('stream')
const PizZip = require('pizzip')
const Docxtemplater = require('docxtemplater')
const AdmZip = require('adm-zip')
const ExcelJS = require('exceljs')

// 模板文件夹路径
const templatesDir = path.join(__dirname, '../public/templates')
const personal_daily_work_template = path.join(templatesDir, 'personal_daily_work_template.docx')
const personal_daily_zs_template = path.join(templatesDir, 'personal_daily_zs_template.xlsx')
const xxmp_template = path.join(templatesDir, 'xxmp_work_template.docx')

// 多人日报导出
const exportMultiDailyWork = async (params) => {
  const date = params.date
  const zip = new AdmZip()
  let users = await userModel.getAllUsers()
  users = users.filter((i) => i.name !== '管理员')
  const content = fs.readFileSync(personal_daily_work_template, 'binary')

  for (let user of users) {
    const fileName = `地市驻商日报-威海分公司-${user.name}-${date}.docx`
    const doc = new Docxtemplater(new PizZip(content), { linebreaks: true })
    const data = await getDailyWorkData({ userId: user.id, date })
    data.date = params.date
    doc.setData(data)
    try {
      doc.render()
      const buffer = doc.getZip().generate({ type: 'nodebuffer' })
      zip.addFile(fileName, buffer)
    } catch (error) {
      throw new Error(`Error replacing in ${fileName}: `, error)
    }
  }

  const zipBuffer = zip.toBuffer()
  const readablestream = new Readable()
  readablestream.push(zipBuffer)
  readablestream.push(null)
  return readablestream
}

// 多人驻商工作导出
const exportMultiZsgzExcel = async (params) => {
  const date = params.date
  const zip = new AdmZip()
  let users = await userModel.getAllUsers()
  users = users.filter((i) => i.name !== '管理员')

  for (let user of users) {
    const fileName = `驻商需求响应清单-威海分公司-${user.name}-${date}.xlsx`
    const data = await workModel.getAllItemsByType({ ...params, userId: user.id }, 3)
    const workbook = new ExcelJS.Workbook()
    const template = path.join(templatesDir, user.name + '.xlsx')
    await workbook.xlsx.readFile(template)
    const sourceSheet = workbook.getWorksheet(1)
    const targetSheet = workbook.addWorksheet('驻商工作表')

    let template_row = null
    sourceSheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
      const targetRow = targetSheet.getRow(rowNumber)
      // 复制最后一行样式
      template_row = row
      row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        const targetCell = targetRow.getCell(colNumber)
        targetCell.value = cell.value
        targetCell.style = { ...cell.style }
      })
    })

    sourceSheet.columns.forEach((column, index) => {
      targetSheet.getColumn(index + 1).width = column.width
    })
    let rowNumber = user.rowIndex
    data.forEach((item, index) => {
      targetSheet.getCell('A' + rowNumber).value = rowNumber - 1
      targetSheet.getCell('B' + rowNumber).value = '威海市'
      targetSheet.getCell('C' + rowNumber).value = item.userName
      targetSheet.getCell('D' + rowNumber).value = item.businessName
      targetSheet.getCell('E' + rowNumber).value = item.content
      targetSheet.getCell('F' + rowNumber).value = item.businessWorkType

      const targetRow = targetSheet.getRow(rowNumber)
      template_row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
        const targetCell = targetRow.getCell(colNumber)
        targetCell.style = { ...cell.style }
      })

      rowNumber++
    })
    workbook.removeWorksheet(1)
    const buffer = await workbook.xlsx.writeBuffer()
    zip.addFile(fileName, buffer)
  }

  const zipBuffer = zip.toBuffer()
  const readablestream = new Readable()
  readablestream.push(zipBuffer)
  readablestream.push(null)
  return readablestream
}

// 单人日报导出
const exportDailyWork = async (params) => {
  // 读取模板文件
  const content = fs.readFileSync(personal_daily_work_template, 'binary')
  // 创建一个新的 Docxtemplater 实例
  const zip = new PizZip(content)
  const doc = new Docxtemplater(zip, { linebreaks: true })
  // 查询数据
  const data = await getDailyWorkData(params)
  data.date = params.date
  // 应用数据到模板
  doc.setData(data)
  // 渲染模板
  doc.render()
  // 生成新的文件并以 Buffer 形式返回
  const buffer = doc.getZip().generate({ type: 'nodebuffer' })
  const readablestream = new Readable()
  readablestream.push(buffer)
  readablestream.push(null)
  // 流的末尾，推送 null 标记结束
  return readablestream
}

// 导出摸排信息表
const exportInfoWorkItems = async (date) => {
  const content = fs.readFileSync(xxmp_template, 'binary')
  const zip = new PizZip(content)
  const doc = new Docxtemplater(zip, { linebreaks: true })
  const data = await workModel.getMpxxItems(date)
  const result = {
    year: new Date(date).getFullYear(),
    month: new Date(date).getMonth() + 1,
    day: new Date(date).getDate(),
    sjxx: data
      .filter((i) => i.infoType == '商机消息')
      .map((v, index) => {
        return { ...v, index: index + 1 }
      }),
    else: data
      .filter((i) => i.infoType !== '商机消息')
      .map((v, index) => {
        return {
          ...v,
          index: index + 1,
          isImportant: v.infoType == '重要消息',
          isNotImportant: v.infoType !== '重要消息'
        }
      })
  }
  doc.setData(result)
  doc.render()
  const buffer = doc.getZip().generate({ type: 'nodebuffer' })
  const readablestream = new Readable()
  readablestream.push(buffer)
  readablestream.push(null)
  return readablestream
}

// 驻商工作表
const exportZsgzExcel = async (params) => {
  // 读取模板文件
  const workbook = new ExcelJS.Workbook()
  await workbook.xlsx.readFile(personal_daily_zs_template)
  // 获取第一个工作表
  const sourceSheet = workbook.getWorksheet(1)
  // 新建工作表
  const targetSheet = workbook.addWorksheet('驻商工作表')
  //复制单元格的值和样式
  sourceSheet.eachRow({ includeEmpty: true }, (row, rowNumber) => {
    const targetRow = targetSheet.getRow(rowNumber)
    row.eachCell({ includeEmpty: true }, (cell, colNumber) => {
      const targetCell = targetRow.getCell(colNumber)
      targetCell.value = cell.value
      targetCell.style = { ...cell.style }
    })
  })
  //更新所有列宽度
  sourceSheet.columns.forEach((column, index) => {
    targetSheet.getColumn(index + 1).width = column.width
  })
  // 获取数据
  const data = await workModel.getAllItemsByType(params, 3)
  // 向工作表中添加数据 序号	地市	驻商人员	驻商单位	需求内容	需求类型
  let rowNumber = 2
  data.forEach((item, index) => {
    targetSheet.getCell('A' + rowNumber).value = index + 1
    targetSheet.getCell('B' + rowNumber).value = '威海市'
    targetSheet.getCell('C' + rowNumber).value = item.userName
    targetSheet.getCell('D' + rowNumber).value = item.businessName
    targetSheet.getCell('E' + rowNumber).value = item.content
    targetSheet.getCell('F' + rowNumber).value = item.businessWorkType
    rowNumber++
  })
  workbook.removeWorksheet(1)
  return workbook.xlsx
}

// 查询并组合日报内容
const getDailyWorkData = async (params) => {
  const results = await workModel.getDetailDailyWork(params)
  if (results.length == 0) throw new Error('当日日报无内容，请先填写保存！')
  const workId = results[0].id
  const dailyWorkItems = await workModel.getAllItemsByWorkId(workId)
  const workItems = resolveWorkList(dailyWorkItems)
  return { ...results[0], ...workItems }
}

// 处理日报条目
const resolveWorkList = (list) => {
  if (list.length == 0) return list
  // 1信息摸排   2商机跟进  3驻商工作
  const result = { xxmp: [], sjgj: [], zsgz: [] }
  let xxmp = 0,
    sjgj = 0,
    zsgz = 0
  list.forEach((item) => {
    if (item.workType == 1) {
      result.xxmp.push({
        ...item,
        index: ++xxmp,
        isImportant: item.infoType == '重要消息',
        isNotImportant: item.infoType !== '重要消息'
      })
    } else if (item.workType == 2) {
      result.sjgj.push({ ...item, index: ++sjgj })
    } else {
      result.zsgz.push({ ...item, index: ++zsgz })
    }
  })

  return result
}

module.exports = {
  exportMultiDailyWork,
  exportMultiZsgzExcel,
  exportDailyWork,
  exportZsgzExcel,
  exportInfoWorkItems
}
